//
//  HBLoginCtrl.m
//  HuoBao
//
//  Created by sky on 15/11/25.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBLoginCtrl.h"
#import "HBDologinParam.h"
#import "HBDologinParser.h"
#import "NetCenter.h"
#import "HBLoginUserInfo.h"
#import "HBLoginManager.h"
#import "HBFindPwdFirstCtrl.h"
#import "NSString+MKNetworkKitAdditions.h"
#import "HBTabBarViewController.h"
#import "CheckValid.h"
#import "HBSetPushAccountManager.h"

#define GetFinalResult(x,y,z,r) (IsIphone4?x:(IsIphone6P?r:(IsIphone5?y:z)))

#define TOTOP     GetFinalResult(160/2,160/2,330/2,330/2)

@interface HBLoginCtrl ()<UITextFieldDelegate>
{
    UIScrollView *_bgview;
    UITextField  *_username;
    UITextField *_password;
    UIButton *_choseOp;
    UIButton *_loginbtn;
    UILabel *_alterlbl;
}
@property (nonatomic, strong) UIButton *clearBtn;
@property (nonatomic, strong) UIButton *passclearBtn;

@end

@implementation HBLoginCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void)buildLayout{
    [self addTap];
    self.title = @"登录";
    
    
    _bgview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _bgview.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    UIImageView *bgimagevi = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, SCREEN_HEIGHT)];
    bgimagevi.image = [UIImage imageNamed:@"login_pubbg"];
    [_bgview addSubview:bgimagevi];
    [self.view addSubview:_bgview];
    
    UIImage *eye = [UIImage imageNamed:@"login_close"];
    
    _username = [self TextFieldWithRect:CGRectMake(40, TOTOP, SCREEN_WIDTH - 80, 40) leftImage:nil placeHold:@"请输入11位手机号" index:1];
    _username.keyboardType = UIKeyboardTypeNumberPad;

    
    UIImage *clearIamge = [UIImage imageNamed:@"login_clearn"];
    self.clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.clearBtn.frame = CGRectMake(_username.size.width+_username.origin.x-clearIamge.size.width, _username.y+(_username.height-clearIamge.size.height)/2, clearIamge.size.width, clearIamge.size.height);
    //    LLog(@"%@",NSStringFromCGRect(clearBtn.frame));
    self.clearBtn.alpha = 0;
    [self.clearBtn setImage:clearIamge forState:UIControlStateNormal];
    [self.clearBtn addTarget:self action:@selector(clickToClearTF:) forControlEvents:UIControlEventTouchUpInside];
    [_bgview addSubview:self.clearBtn];
    [_bgview bringSubviewToFront:self.clearBtn];


    
    _password = [self TextFieldWithRect:CGRectMake(40, _username.origin.y + 15 + 15 + 18, SCREEN_WIDTH - 102/2 - eye.size.width - 20 - 20, 40) leftImage:nil placeHold:@"请输入密码" index:2];
    _password.secureTextEntry = YES;
    
    
    self.passclearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.passclearBtn.frame = CGRectMake(_password.size.width+_password.origin.x-clearIamge.size.width, _password.y+(_password.height-clearIamge.size.height)/2, clearIamge.size.width, clearIamge.size.height);
    //    LLog(@"%@",NSStringFromCGRect(clearBtn.frame));
    self.passclearBtn.alpha = 0;
    [self.passclearBtn setImage:clearIamge forState:UIControlStateNormal];
    [self.passclearBtn addTarget:self action:@selector(clickToClearTF:) forControlEvents:UIControlEventTouchUpInside];
    [_bgview addSubview:self.passclearBtn];
    [_bgview bringSubviewToFront:self.passclearBtn];
    
    
    
    _alterlbl = [self LabelWithRect:CGRectMake(40, _password.origin.y + 40 + 2 + 17, SCREEN_HEIGHT - 80, 12) textColor:[LCCommon getColor:@"fff25e"] textstr:@"" textfont:12 textstyle:NSTextAlignmentLeft];
    [_bgview addSubview:_alterlbl];
    
    _choseOp = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 102/2 - eye.size.width, _password.origin.y - 13 + 13, eye.size.width, eye.size.height)];
    _choseOp.tag = 1024;
    [_choseOp addTarget:self action:@selector(choseCloseOrOpen:) forControlEvents:UIControlEventTouchUpInside];
    [_choseOp setBackgroundImage:eye forState:UIControlStateNormal];
    [_bgview addSubview:_choseOp];
    
    
    _loginbtn = [[UIButton alloc]initWithFrame:CGRectMake(40, _password.origin.y + 40 + 2 + 45, SCREEN_WIDTH - 80, 45)];
    [_loginbtn setBackgroundColor:[LCCommon getColor:Btn_Normal] forState:UIControlStateNormal];
    [_loginbtn setBackgroundColor:[LCCommon getColor:Btn_Selected] forState:UIControlStateHighlighted];
    [_loginbtn setBackgroundColor:[LCCommon getColor:Btn_Disable] forState:UIControlStateDisabled];
    _loginbtn.enabled = NO;
    [_loginbtn setTitle:@"登录" forState:UIControlStateNormal];
    _loginbtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [_loginbtn setTitleColor:[LCCommon getColor:@"070707"] forState:UIControlStateNormal];
    _loginbtn.clipsToBounds = YES;
    _loginbtn.layer.cornerRadius = 4;
    [_loginbtn addTarget:self action:@selector(btntologin) forControlEvents:UIControlEventTouchUpInside];
    [_bgview addSubview:_loginbtn];
    
    
    UILabel *forget = [self LabelWithRect:CGRectMake(SCREEN_WIDTH - 40 - 48, _loginbtn.origin.y + 45 , 4 * 12, 13 + 24) textColor:[LCCommon getColor:@"5e5e5e"] textstr:@"忘记密码" textfont:12 textstyle:NSTextAlignmentCenter];
    forget.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(topToforget)];
    [forget addGestureRecognizer:tap];
    [_bgview addSubview:forget];
    
    if (self.navigationController.viewControllers[0] == self) {
        [self showDoneWithTitle:@"跳过"];
    }else{
//        [self showCustomNavWithColorString:@"e1e1e1" title:@"登录" titleFont:[UIFont systemFontOfSize:22] leftBackButtonShow:YES rightBtnShow:YES];
    }
}

-(void)doDone{
    HBTabBarViewController *tab = [[HBTabBarViewController alloc]init];
    [UIApplication sharedApplication].keyWindow.rootViewController = tab;
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
//    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
//        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
//    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
//    if (self.navigationController.viewControllers[0] == self) {
//        self.navigationController.navigationBarHidden = NO;
//    }else{
//        self.navigationController.navigationBarHidden = YES;
//    }
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    //    [self.navigationItem setHidesBackButton:YES];
    //    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    //        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    //    }
    //
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                name:UITextFieldTextDidChangeNotification
                                              object:_username];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextFieldTextDidChangeNotification object:nil];
}



-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)doTouch:(UIGestureRecognizer *)sender{
    self.clearBtn.alpha = 0;
    self.passclearBtn.alpha = 0;
    [self.view endEditing:YES];
}


- (void)showCustomNavWithColorString:(NSString*)colorString title:(NSString*)title titleFont:(UIFont*)font leftBackButtonShow:(BOOL)leftShow rightBtnShow:(BOOL)rightShow{
    UIView* navBack = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [navBack setBackgroundColor:[LCCommon getColor:@"000000"]];
    [self.view addSubview:navBack];
    
    UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH - 80, 44)];
    titleLabel.centerX = navBack.centerX;
    titleLabel.font = font;
    titleLabel.text = title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [LCCommon getColor:@"ffffff"];
    [navBack addSubview:titleLabel];
    
    
    UIButton* leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setFrame:CGRectMake(15, 30, 13, 22)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [navBack addSubview:leftBtn];
    [leftBtn addTarget:self action:@selector(leftbtnClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)leftbtnClicked:(UIButton*)button{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - textfiled

-(void)textDidChange{
    if (_username.text.length > 0 || _password.text.length > 0) {
        _loginbtn.enabled = YES;
    }else{
        _loginbtn.enabled = NO;
    }
}


#pragma mark - topToforget

-(void)topToforget{
    HBFindPwdFirstCtrl  *find = [[HBFindPwdFirstCtrl alloc]init];
    [self.navigationController pushViewController:find animated:YES];
}


#pragma mark - btntologin

-(void)btntologin{    //#pragma mark 下面的代码，在公司打开即可;如果回家可以注释下面的，打开上面的
    NSString *username = _username.text;
    //    NSString *password = _passworkText.text;
    NSString *code = _password.text;
    if ([LCCommon checkIsEmptyString:username]) {
        //        DISSMISS_ERR(@"请输入手机号");
        //DISSMISS_ERRView(@"请输入手机号",[[[UIApplication sharedApplication] windows] lastObject]);
        _alterlbl.text = @"请输入手机号";
        return;
    }
    if (![[NSString stringWithFormat:@"%lld",username.longLongValue] isEqualToString:username]) {
        //        DISSMISS_ERR(@"请输入11位数字格式手机号");
        //DISSMISS_ERRView(@"请输入11位数字格式手机号",[[[UIApplication sharedApplication] windows] lastObject]);
        _alterlbl.text = @"请输入11位数字格式手机号";
        return;
    }
    if (username.length != 11) {
        //        DISSMISS_ERR(@"请输入11位数字格式手机号");
        //DISSMISS_ERRView(@"请输入11位数字格式手机号",[[[UIApplication sharedApplication] windows] lastObject]);
        _alterlbl.text = @"请输入11位数字格式手机号";
        return;
    }
    if (![CheckValid isOnlyNumber:username]) {
        _alterlbl.text = @"请输入正确手机号";
        return;
    }
    if ([LCCommon checkIsEmptyString:code]) {
        //        DISSMISS_ERR(@"请输入验证码");
        //DISSMISS_ERRView(@"请输入验证码",[[[UIApplication sharedApplication] windows] lastObject]);
        _alterlbl.text = @"请输入密码";
        return;
    }
    [self.view endEditing:YES];
    [self requestToLogin];
}



-(void)requestToLogin{
    HBDologinParam *param = [[HBDologinParam alloc]init];
    param.mobile = _username.text;
    param.password = _password.text.md5;
    LLog(@"%@",_password.text.md5);
    HBDologinParser *parser = [[HBDologinParser alloc]init];
    [CustomLoadingView showHudToView:self.view];
    [NetCenter postDataFromURL:Method_login params:param parser:parser result:^(ParserResult *myResult) {
        [CustomLoadingView hideHudForView:self.view];
        if (myResult.code == 0)
        {
            HBLoginUserInfo *info = (HBLoginUserInfo *)myResult.result;
            [HBLoginManager cacheCurrentUserToUserDefault:info];
            
            [HBSetPushAccountManager requestToSetPushAccountWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
                
            }];
            
            HBTabBarViewController *tab = [[HBTabBarViewController alloc]init];
            [UIApplication sharedApplication].keyWindow.rootViewController = tab;
        }
        else
        {
            _alterlbl.text = (myResult.message);
        }
        
        
    } failure:^(NSError *error) {
        [CustomLoadingView hideHudForView:self.view];
        DISSMISS_ERR([error description]);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.
}


-(void)choseCloseOrOpen:(UIButton *)sender{
    UIImage *open = [UIImage imageNamed:@"login_open"];
    UIImage *close = [UIImage imageNamed:@"login_close"];
    if (sender.tag == 1024) {
        _choseOp.tag = 1025;
        _choseOp.frame = CGRectMake(SCREEN_WIDTH - 102/2 - open.size.width, _password.origin.y - 8 + 13, open.size.width, open.size.height);
        _password.secureTextEntry = NO;
        [_choseOp setBackgroundImage:open forState:UIControlStateNormal];
    }else if(sender.tag == 1025){
        _choseOp.tag = 1024;
        _choseOp.frame = CGRectMake(SCREEN_WIDTH - 102/2 - open.size.width, _password.origin.y - 13 + 13, open.size.width, open.size.height);
        _password.secureTextEntry = YES;
        [_choseOp setBackgroundImage:close forState:UIControlStateNormal];
    }
}


- (UITextField *)TextFieldWithRect:(CGRect)rect leftImage:(UIImage *)image placeHold:(NSString *)placeHold index:(NSInteger)index
{
    UITextField *text = [[UITextField alloc] initWithFrame:rect];
    text.placeholder = placeHold;
    text.backgroundColor = [UIColor clearColor];
    text.delegate = self;
    text.font = [UIFont systemFontOfSize:15];
    text.textColor = [LCCommon getColor:@"ffffff"];
    [text setValue:[LCCommon getColor:@"5e5e5f"] forKeyPath:@"_placeholderLabel.textColor"];
    [_bgview addSubview:text];
    UIView *line = [[UIView alloc]init];
    if (index == 1) {
        line = [[UIView alloc] initWithFrame:CGRectMake(40, rect.size.height + rect.origin.y + 2, rect.size.width, .5)];
    }else{
        line = [[UIView alloc] initWithFrame:CGRectMake(40, rect.size.height + rect.origin.y + 2, SCREEN_WIDTH - 80, .5)];
    }
   
    line.backgroundColor = [LCCommon getColor:@"a8a8a8"];
    [_bgview addSubview:line];
    line = nil;
    return text;
}

-(UILabel *)LabelWithRect:(CGRect)rect textColor:(UIColor *)color textstr:(NSString *)str textfont:(int)font textstyle:(NSTextAlignment)aligment{
    UILabel *label = [[UILabel alloc] initWithFrame:rect];
    label.textColor = color;
    label.text = str;
    label.font = [UIFont systemFontOfSize:font];
    label.textAlignment = aligment;
    label.numberOfLines = 0;
    return label;
}



#pragma mark -
#pragma mark - textFiled

- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    /*
     Restore the size of the text view (fill self's view).
     Animate the resize so that it's in sync with the disappearance of the keyboard.
     */
    
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView animateWithDuration:animationDuration animations:^{
        //        CGRect frame = self.view.frame;
        //        frame.origin.y = 0;
        //        self.view.frame = frame;
        
        CGPoint contentOffset = _bgview.contentOffset;
        contentOffset.y = 0;
        _bgview.contentOffset = contentOffset;
    }];
    self.clearBtn.alpha = 0;
    self.passclearBtn.alpha = 0;
    _bgview.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
}

- (void)keyboardWillShow:(NSNotification *)notification {
    
    UITextField *text ;
    for (UITextField *field in _bgview.subviews) {
        if (field.isFirstResponder) {
            text = field;
        }
    }
    
    NSDictionary *userInfo = [notification userInfo];
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    // Get the duration of the animation.
    
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [UIView animateWithDuration:animationDuration animations:^{

        
        LLog(@"_bgview.contentOffSet:%@",NSStringFromCGPoint(_bgview.contentOffset));
        if (text.size.height == 0) {
            
            
        }else if (CGRectGetMaxY(text.frame)+CGRectGetMinY(_bgview.frame) - _bgview.contentOffset.y <= SCREEN_HEIGHT - 64 - (keyboardRect.size.height+30)){
            
            
        }else{
            
            CGPoint contentOffset = _bgview.contentOffset;
            contentOffset.y += (CGRectGetMaxY(text.frame)+CGRectGetMinY(_bgview.frame) - _bgview.contentOffset.y) - (SCREEN_HEIGHT - 64 - (keyboardRect.size.height+30));
            _bgview.contentOffset = contentOffset;
            
        }
        
    }];
    
    CGSize contentSize = _bgview.contentSize;
    contentSize.height = _bgview.bounds.size.height + keyboardRect.size.height;
    _bgview.contentSize = contentSize;
    
    
}


-(void)textFiledEditChanged:(NSNotification *)obj{
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBeString = textField.text;
    
    UITextInputMode *currentInputMode = _username.textInputMode;
    NSString *lang = [currentInputMode primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 11) {
                _username.text = [toBeString substringToIndex:11];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > 11) {
            _username.text = [toBeString substringToIndex:11];
        }
    }
}




#pragma mark -
#pragma mark - active

- (void)clickToClearTF:(UIButton *)sender
{
    if ([_username isFirstResponder])
    {
        _username.text = @"";
    }
    else
    {
        _password.text = @"";
    }
    [self textDidChange];
}

#pragma mark - textfiledDedate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField == _username) {
        self.passclearBtn.alpha = 0;
        self.clearBtn.alpha = 1;
    }else if (textField == _password){
        self.clearBtn.alpha = 0;
        self.passclearBtn.alpha = 1;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
